import Https from "@/utils/Https";
import { InfoCircleOutlined } from "@ant-design/icons";
import { CheckCard } from "@ant-design/pro-components";
import {
  Button,
  Checkbox,
  Descriptions,
  Divider,
  InputNumber,
  Modal,
  Tooltip,
  Spin,
  message,
} from "antd";
import { FC, useEffect, useState } from "react";
import { BtnList, TooltipList } from "./configFile";
import { history } from "umi";
import styles from "./index.less";
import dayjs from "dayjs";
const OrderModal: FC<any> = (props) => {
  //type 1 购买 2升级 3加购 4续费
  const { open, title, type, onClose, activeKey } = props;
  const [loading, setLoading] = useState(false);
  const [minVenueNum, setMinVenueNum] = useState(0);
  const [checked, setChecked] = useState(false);
  const [packageDetails, setPageageDetails] = useState<any>({});
  //选中套餐信息
  const [packageInfo, setPackageInfo] = useState<any>({});
  //选中购买时长信息
  const [buyTimeInfo, setBuyTimeInfo] = useState<any>({});
  //场馆数量
  const [venueNum, setVenueNum] = useState(0);
  const [price, setPrice] = useState(0);
  const [discountPrice, setDiscountPrice] = useState(0);
  //获取可升级套餐详情
  const getPackageDetails = async () => {
    setLoading(true);
    let url =
      type == "2"
        ? "/band/package/upgradePackageDetail"
        : type == "3"
        ? "/band/package/additionalVenueDetail"
        : "/band/package/renewalPackageDetail";
    let res = await Https.get(url, {}, true);
    console.log(res, "-res");
    if (res.code == 200) {
      setPageageDetails(res.data);
      if (type == "3") {
        setPackageInfo({
          packageName: res.data.packageName,
          additionalVenuePrice: res.data.additionalVenuePrice,
          id: res.data.id,
          venueNum: res.data.venueNum,
          expireTime: res.data.expireTime,
        });
        setVenueNum(1);
        setMinVenueNum(1);
        setBuyTimeInfo({
          effectiveDate: 1,
          discountRate: 100,
          id: res.data.id,
        });
      }
      if (type == "4") {
        setPackageInfo(res.data.upgradePackageList[0]);
        let count =
          res.data.tenantVenueNum - res.data.upgradePackageList[0].venueNum;
        if (count > 0) {
          setVenueNum(res.data.tenantVenueNum);
          setMinVenueNum(res.data.tenantVenueNum);
        } else {
          setVenueNum(res.data.upgradePackageList[0].venueNum);
          setMinVenueNum(res.data.upgradePackageList[0].venueNum);
        }
      }
    } else {
      setPageageDetails({});
      message.error(res.msg);
    }
    setLoading(false);
  };
  //获取价格
  const getPrice = async (orderType, packageInfo, buyTimeInfo, venueNum) => {
    let params = {
      packageId: packageInfo.id,
      packageSkuId: buyTimeInfo.id,
      orderType,
      venueNum,
    };
    let res = await Https.get("/band/package/getFinalAmount", params, true);
    console.log(res, "_res");
    if (res.code == 200) {
      setPrice(res.data.originalPrice);
      setDiscountPrice(res.data.sellPrice);
    } else {
      setPrice(0);
      setDiscountPrice(0);
      message.error(res.msg);
    }
  };
  //立即下单
  const submit = async () => {
    let params = {
      packageId: packageInfo.id,
      packageSkuId: buyTimeInfo.id ? buyTimeInfo.id : "",
      orderType: type,
      venueNum,
      oldRecordId: packageDetails.oldRecordId ? packageDetails.oldRecordId : "",
    };
    setLoading(true);
    let res = await Https.get("/band/package/createOrder", params, true);
    setLoading(false);
    console.log(res, "-res");
    if (res.code == 200) {
      history.push(`/brand/order/${res.data}/${activeKey}`);
    } else {
      message.error(res.msg);
    }
  };
  useEffect(() => {
    setPackageInfo({});
    setBuyTimeInfo({});
    setVenueNum(0);
    setMinVenueNum(0);
    setChecked(false);
    setPrice(0);
    setDiscountPrice(0);
    if (open) {
      getPackageDetails();
    }
  }, [open]);
  useEffect(() => {
    if (packageInfo.id && buyTimeInfo.id && venueNum > 0) {
      getPrice(type, packageInfo, buyTimeInfo, venueNum);
    }
  }, [type, packageInfo, buyTimeInfo, venueNum]);
  return (
    <Modal
      open={open}
      title={title}
      onCancel={() => {
        onClose();
      }}
      width="80%"
      wrapClassName={styles.orderClass}
      destroyOnClose={true}
      footer={null}
    >
      <Spin spinning={loading}>
        <div className={styles.orderMain}>
          <div className={styles.orderMainLeft}>
            <div className={styles.orderTitle}>
              {packageDetails.packageName}
            </div>
            <div
              className={styles.orderDesc}
              title={packageDetails.packageIntroduce}
            >
              {packageDetails.packageIntroduce}
            </div>
            <Divider />
            <div className={styles.orderFunction}>
              {packageDetails.functionDescriptions &&
                packageDetails.functionDescriptions.length > 0 &&
                packageDetails.functionDescriptions.map((item, index) => (
                  <span key={index} title={item}>
                    {item}
                  </span>
                ))}
            </div>
          </div>
          <div className={styles.orderMainMidden}>
            <div className={styles.orderTitle}>选择套餐</div>
            {(type == "2" || type == "4") && (
              <div>
                <div className={styles.orderMiddenCheck}>
                  <CheckCard.Group
                    onChange={(value) => {
                      console.log(value);
                      setBuyTimeInfo({});
                      if (value) {
                        let obj = packageDetails.upgradePackageList.filter(
                          function (o) {
                            return o.id == value;
                          }
                        )[0];
                        console.log("value", obj, value);
                        setPackageInfo(obj);
                        let count =
                          packageDetails.tenantVenueNum - obj.venueNum;
                        if (count > 0) {
                          setVenueNum(packageDetails.tenantVenueNum);
                          setMinVenueNum(packageDetails.tenantVenueNum);
                        } else {
                          setVenueNum(obj.venueNum);
                          setMinVenueNum(obj.venueNum);
                        }
                      } else {
                        setPackageInfo({});
                        setVenueNum(0);
                        setMinVenueNum(0);
                      }
                    }}
                    value={packageInfo.id}
                  >
                    {packageDetails.upgradePackageList &&
                      packageDetails.upgradePackageList.length > 0 &&
                      packageDetails.upgradePackageList.map((item) => (
                        <CheckCard
                          title={item.packageName}
                          key={item.id}
                          description={`¥${
                            item.additionalVenuePrice / 100
                          }/场馆/月`}
                          value={item.id}
                          style={{ pointerEvents: type != "2" ? "none" : "" }}
                        />
                      ))}
                  </CheckCard.Group>
                </div>
                {packageInfo.id && (
                  <>
                    <div className={styles.orderTitle}>
                      购买时长
                      {type == "4" && (
                        <span
                          style={{
                            marginLeft: "5px",
                            color: "#666666",
                            fontSize: "16px",
                            fontWeight: "normal",
                          }}
                        >
                          (服务到期时间
                          {packageDetails.expireTime
                            ? dayjs(packageDetails.expireTime).format(
                                "YYYY-MM-DD"
                              )
                            : "-"}
                          )
                        </span>
                      )}
                    </div>
                    <div
                      className={[
                        styles.orderMiddenCheck,
                        styles.orderTimeCheck,
                      ].join(" ")}
                    >
                      <CheckCard.Group
                        onChange={(value) => {
                          if (value) {
                            let obj = packageInfo.skuList.filter(function (o) {
                              return o.id == value;
                            })[0];
                            setBuyTimeInfo(obj);
                            console.log("value", obj, value);
                          } else {
                            setBuyTimeInfo({});
                          }
                        }}
                      >
                        {packageInfo.skuList &&
                          packageInfo.skuList.length > 0 &&
                          packageInfo.skuList.map((item) => (
                            <div style={{ position: "relative" }}>
                              <CheckCard
                                title={item.effectiveDate + "个月"}
                                key={item.id}
                                value={item.id}
                              />
                              {Number(item.discountRate) < 100 && (
                                <div className={styles.orderDiscount}>
                                  {Number(item.discountRate) / 10}折
                                </div>
                              )}
                            </div>
                          ))}
                      </CheckCard.Group>
                    </div>
                  </>
                )}
              </div>
            )}
            {type == "3" && (
              <>
                <div className={styles.orderMiddenCheck}>
                  <CheckCard
                    title={packageInfo.packageName}
                    key={packageInfo.id}
                    description={`¥${
                      packageInfo.additionalVenuePrice / 100
                    }/场馆/月`}
                    value={packageInfo.id}
                    defaultChecked
                    style={{ pointerEvents: "none" }}
                  />
                </div>
                <div className={styles.orderTitle}>服务到期时间</div>
                <div className={styles.orderMiddenCheck}>
                  <CheckCard
                    title={dayjs(packageDetails.expireTime).format(
                      "YYYY-MM-DD"
                    )}
                    defaultChecked
                    style={{ pointerEvents: "none" }}
                  />
                </div>
              </>
            )}
            {(packageInfo.id || type != "2") && (
              <>
                <div className={styles.orderTitle}>
                  场馆数量
                  {type != "2" && (
                    <span
                      style={{
                        marginLeft: "5px",
                        color: "#666666",
                        fontSize: "16px",
                        fontWeight: "normal",
                      }}
                    >
                      (当前场馆数量{packageDetails.tenantVenueNum}个)
                    </span>
                  )}
                </div>
                <div>
                  <InputNumber
                    min={minVenueNum}
                    max={1000}
                    value={venueNum}
                    precision={0}
                    addonAfter="个"
                    style={{ width: "150px" }}
                    onChange={(e) => {
                      if (e) {
                        setVenueNum(e);
                      } else {
                        setVenueNum(minVenueNum);
                      }
                    }}
                  />
                </div>
                <div className={styles.orderMiddenTips}>
                  <span>如果您选择了10 则可创建/使用的场馆总数为10个;</span>
                  <span>不同版本的场馆价格不同, 升级版本时需要补齐价格差;</span>
                </div>
              </>
            )}
          </div>
          <div className={styles.orderMainRight}>
            <div className={styles.orderTitle}>订单详情</div>
            <Descriptions title="" column={1}>
              <Descriptions.Item label="品牌名称">
                {packageDetails.brandName}
              </Descriptions.Item>
              <Descriptions.Item label="订单类型">
                {type == "3" ? "加购场馆" : BtnList[type]}
              </Descriptions.Item>
              <Descriptions.Item label="套餐名称">
                {packageInfo.packageName ? packageInfo.packageName : "-"}
              </Descriptions.Item>
              {type != "3" && (
                <Descriptions.Item label="购买时长">
                  {buyTimeInfo.effectiveDate
                    ? buyTimeInfo.effectiveDate + "个月"
                    : "-"}
                </Descriptions.Item>
              )}
              {type == "3" && (
                <Descriptions.Item label="到期时间">
                  {packageDetails.expireTime
                    ? dayjs(packageDetails.expireTime).format("YYYY-MM-DD")
                    : "-"}
                </Descriptions.Item>
              )}
              <Descriptions.Item
                label={type == "3" ? "加购场馆数量" : "场馆数量"}
              >
                {venueNum ? venueNum + "个" : "-"}
              </Descriptions.Item>
            </Descriptions>
            <div className={styles.orderMainPay}>
              <Descriptions title="" column={1}>
                <Descriptions.Item
                  label={
                    <span>
                      实际支付
                      {packageInfo.id && buyTimeInfo.id && venueNum > 0 && (
                        <Tooltip
                          title={
                            type == 3
                              ? `加购场馆数量(${venueNum}) * 加购场馆价格(¥${
                                  packageInfo.additionalVenuePrice / 100
                                })/31天 * 剩余天数  = 实际支付(¥${discountPrice})`
                              : `场馆数量(${venueNum}) * 单价(¥${
                                  packageInfo.additionalVenuePrice / 100
                                }) * 时长(${
                                  buyTimeInfo.effectiveDate
                                })个月 * 折扣系数(${
                                  buyTimeInfo.discountRate / 100
                                }) = 实际支付(¥${discountPrice})`
                          }
                        >
                          <InfoCircleOutlined style={{ marginLeft: "5px" }} />
                        </Tooltip>
                      )}
                    </span>
                  }
                >
                  {packageInfo.id && buyTimeInfo.id ? (
                    <span style={{ color: "red", fontWeight: "bold" }}>
                      {"¥" + discountPrice}
                    </span>
                  ) : (
                    "-"
                  )}
                </Descriptions.Item>
                {(type == "2" || type == "4") && (
                  <Descriptions.Item label="原价">
                    {packageInfo.id && buyTimeInfo.id ? (
                      <span>{"¥" + price}</span>
                    ) : (
                      "-"
                    )}
                  </Descriptions.Item>
                )}
              </Descriptions>
            </div>
            <div className={styles.orderSave}>
              <Button
                type="primary"
                disabled={
                  !checked ||
                  !packageInfo.id ||
                  !buyTimeInfo.id ||
                  discountPrice == 0
                }
                onClick={() => {
                  submit();
                }}
              >
                立即下单
              </Button>
            </div>
            <div className={styles.orderSave}>
              <Checkbox
                checked={checked}
                onChange={(e) => {
                  let { checked } = e.target;
                  setChecked(checked);
                }}
              >
                我已阅读并同意 <a href="">《服务协议》</a>
              </Checkbox>
            </div>
          </div>
        </div>
      </Spin>
    </Modal>
  );
};
export default OrderModal;
